package com.ringtheweb.common.util;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Utility class to deal with exceptions
 * @author ldewavri
 *
 */
public abstract class ThrowableUtils {

	 /**
     * Create a String with the stack trace of a {@link Throwable}
     * @param t a {@link Throwable}
     * @return a {@link String}
     */
    public static String stackTraceAsString(Throwable t) {
    	StringWriter sw = new StringWriter();
    	PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
    	return sw.toString();
    }
    
    /**
     * Dump {@link Throwable} message into a formatted String  
     * @param t a {@link Throwable}
     * @return a {@link String}
     */
    public static String throwableToString(Throwable t) {
		return throwableToString(t, t.getCause());
	}
    
    /**
     * Dump {@link Throwable} message into a formatted String with its cause
     * @param t a {@link Throwable}
     * @return a {@link String}
     */    
    private static String throwableToString(Throwable origin, Throwable cause) {
		if  (origin == null)
			return "";
		
		if (cause == null)
			return name(origin)
			+ message(origin);
		
		return
			throwableToString(cause, cause.getCause()) + "\ncaused... "
			+ name(origin)
			+ message(origin);
			
    }
	
	private static String name(Throwable t) {
		return "\n\n[EXCEPTION]  " + t.getClass().getName() +"\n"; 
	}
	
	private static String  message(Throwable t) {
		return "[MESSAGE] " + t.getMessage() + "\n";
	}
	
}
